package com.geostar.constructionland.statistics.service.factory.impl;

import com.geostar.constructionland.common.entity.statistics.UnifiedDataQueryConfig;
import com.geostar.constructionland.statistics.mapping.QueryMappedStatement;
import com.geostar.constructionland.statistics.mapping.SqlStatement;
import com.geostar.constructionland.statistics.service.factory.ISqlCustomWorker;
import org.apache.ibatis.mapping.SqlCommandType;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author makoto_zhu
 * @Date 2020-12-18 04:06:38
 * @Description
 **/
@Component
public class SqlCustomWorkerImpl implements ISqlCustomWorker {
    @Override
    public void createSql(QueryMappedStatement queryMappedStatement, UnifiedDataQueryConfig unifiedDataQueryConfig) {
        SqlStatement sqlStatement = new SqlStatement();
        sqlStatement.setUniqueQueryId(unifiedDataQueryConfig.getUniqueQueryId());

        switch (unifiedDataQueryConfig.getType()) {
            case SQL:
                sqlStatement.setSql(unifiedDataQueryConfig.getSqlVal());
                sqlStatement.setSqlCommandType(determineSqlType(sqlStatement.getSql()));
                break;
            case TABLE:
                String generatedSql = generateSql(unifiedDataQueryConfig.getTableName(), unifiedDataQueryConfig.getFieldName(), queryMappedStatement.getQueryParam());
                sqlStatement.setSql(generatedSql);
                sqlStatement.setSqlCommandType(SqlCommandType.SELECT);
                break;
        }

        queryMappedStatement.setSqlStatement(sqlStatement);
    }


    // 生成sql语句
    private String generateSql(String tableName, String fieldName, Map<String, Object> params) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("select " + fieldName + " from " + tableName + " where 1 = 1");
        if (params.size() > 0) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                stringBuilder.append(" and " + entry.getKey() + "=" + ":" + entry.getKey() + "\n");
            }
        }
        return stringBuilder.toString();
    }

    // 判断sql语句类型
    private SqlCommandType determineSqlType(String sql) {
        sql = sql.trim().toLowerCase();
        if (sql.startsWith("select")) {
            return SqlCommandType.SELECT;
        } else if (sql.startsWith("insert")) {
            return SqlCommandType.INSERT;
        } else if (sql.startsWith("update")) {
            return SqlCommandType.UPDATE;
        } else {
            return SqlCommandType.UNKNOWN;
        }
    }
}
